<?php

require('pagina.php');
require('database.php');
require('auth.php');
require('core.php');

/* get employee data */
include('employee_get_data.php');

// Verifica acao readmit(contratar)
if (!$admin_page && isset($_GET['readmit']) && $employee['leaved'] && nivelAutenticado() >= 3)
{
	query_bd("UPDATE employees SET admitted=NOW(), leaved=NULL WHERE id='{$employee['id']}' LIMIT 1");
	$employee['admitted'] = date("Y-m-d");
	$employee['leaved'] = Null;
}
// Verifica acao fire(despedir)
else if (!$admin_page && isset($_GET['fire']) && !$employee['leaved'] && nivelAutenticado() >= 3)
{
	query_bd("UPDATE employees SET leaved=NOW() WHERE id='{$employee['id']}' LIMIT 1");
	$employee['leaved'] = date("Y-m-d");
}

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - Main Page');
adicionar_css('employee.css');
adicionar_css('datechooser.css');
adicionar_js('datechooser.js');
pagina_head();

// Mostra menu com opcoes do funcionario
if (!$admin_page)
{
    echo "<ul id=opcoes>";
    if ($employee['id'] == $_SESSION[site_id]['id'])
        echo "<li><a href='employee_password.php?id={$employee['id']}'><img src='img/password.gif' alt=''>Change password</a></li>";

    if (nivelAutenticado() >= 3 || edit_self_data)
        echo "<li><a href='employee_edit.php?id={$employee['id']}'><img src='img/edit.png' alt=''>Edit data</a></li>";

    if (nivelAutenticado() >= 3)
    {
        if ($employee['leaved'])
            echo "<li class='positive'><a href='employee.php?id={$employee['id']}&amp;readmit=1'><img src='img/ok.png' alt=''>Readmit employee</a></li>";
        else
            echo "<li class='negative'><a href='employee.php?id={$employee['id']}&amp;fire=1' " .
            "onClick='return confirm(\"Do you really want to fire this employee?\");'>".
            "<img src='img/cancel.png' alt=''>Fire employee</a></li>";
    //	echo "<li><a href='reports.php?manager={$employee['id']}'><img src='img/report.png' alt=''>Reports managed</a></li>";
        echo "<li><a href='incomes_expenses.php?employee={$employee['id']}'><img src='img/payday.png' alt=''>Incomes and Expenses</a></li>";
    }

    echo "<li><a href='employee.php?id={$employee['id']}",
        (isset($_GET['from'])? "&amp;from={$_GET['from']}" : ""),
        (isset($_GET['to'])? "&amp;to={$_GET['to']}" : ""),
        (@$_GET['period']? "&amp;period=" . @$_GET['period'] : ""),
        (@$_GET['location']? "&amp;location=" . @$_GET['location'] : ""),
        "&amp;print=1' target='_blank' ><img src='img/print.png' alt=''>Print</a></li>";

    echo "<li><a href='employee_table.php?id={$employee['id']}",
        (isset($_GET['from'])? "&amp;from={$_GET['from']}" : ""),
        (isset($_GET['to'])? "&amp;to={$_GET['to']}" : ""),
        (@$_GET['period']? "&amp;period=" . @$_GET['period'] : ""),
        (@$_GET['location']? "&amp;location=" . @$_GET['location'] : ""),
        "' target='_blank' ><img src='img/excel.png' alt=''>Excel Table</a></li>";
    echo "</ul><br><br>";
}

// Mostra mensagens broadcast
$messages = query_bd("SELECT * FROM messages WHERE show_home=TRUE ORDER BY posted DESC");

if (mysql_affected_rows() > 0)
{
    echo "<table id=messages>";
    echo "<caption><em>Messages</em></caption>";

	$mark = False;
    while ($message = mysql_fetch_array($messages))
    {
        flush();	/* Manda o que ja tem em buffer para o cliente */

        echo "<tr ", ($mark = !$mark? "class=mark" : ""), ">";

        $dono_da_mensagem = (nivelAutenticado() >= 3 || $_SESSION[site_id]['id'] == $message['employee_id']);

        echo "<td class=first>",
        ($message['employee_id'] != 0 && $dono_da_mensagem? 
            "<a href='employee.php?id={$message['employee_id']}'>" : "");

        /* Gets user name */	
        $contact = ($message['employee_id'] == 0? Array('name'=>'Admin') :
                    query_fetch("SELECT contacts.name FROM contacts, employees WHERE " .
                    "employees.contact_id=contacts.id AND employees.id={$message['employee_id']}"));

        if (!isset($_GET['print']))
        {
            /* if message from admin, shows system logo */
            if ($message['employee_id'] == 0)
            {
                echo "<img class=employee_picture src='img/icone.png' alt='Admin'>";
            }
            else
            {
                $empl_picture = query_fetch("SELECT has_picture FROM employees WHERE id={$message['employee_id']} LIMIT 1");

                echo "<img class=employee_picture src='",
                    ($empl_picture['has_picture']? "portrails/{$message['employee_id']}_thumb.jpg" : "portrails/unknown_thumb.png"),
                    "' alt=''>";
            }
            echo "<br>";
        }
        echo "<p>{$contact['name']}</p>", 
             ($message['employee_id'] != 0 && $dono_da_mensagem? "</a>" : "");

        echo "<td class=second><p>", nl2br(htmlspecialchars(strip_tags($message['content']))), "</p>";
        echo "<small>posted in ", $message['posted'], "</small>";
    }
    unset($messages);

    echo "</table>";
}


// Renderiza dados fixo do funcionario
echo "<div class=dados_estaticos>";
if ($admin_page)
    echo "<h1>System Admin</h1>";
else
{
    echo "<h1>Employee</h1><br>";
    echo "<a href='",
        ($employee['has_picture']? "portrails/{$employee['id']}.jpg" : "portrails/unknown.png"), "'>",
        "<img id=picture src='",
        ($employee['has_picture']? "portrails/{$employee['id']}.jpg" : "portrails/unknown.png"),
        "' alt='No picture uploaded'></a>";
    echo "<dl>";
    echo "<dt>Name</dt><dd>{$contato_employee['name']}",
        ($employee['leaved']? "<span class=negativo>(Fired)</span>" : ""), "</dd>";

    if ($employee['leaved'])
        echo "<dt>Leaved</dt><dd>", date("M j Y", strtotime($employee['leaved'])), "</dd>";
    else
        echo "<dt>Admitted</dt><dd>", date("M j Y", strtotime($employee['admitted'])),  "</dd>";

    echo ($employee['payrate']? "<dt>Fixed payrate</dt><dd>" . show_money($employee['payrate']) . "</dd>" : "");

    echo "<dt>Address</dt><dd><address>",
    "{$contato_employee['number']}, {$contato_employee['street']}, {$contato_employee['complement']} ",
    "zip: {$contato_employee['zipcode']}, {$contato_employee['city']} - {$contato_employee['state']}.</address></dd>";
    if ($contato_employee['phone'])
        echo "<dt>Phone number</dt><dd>{$contato_employee['phone']}</dd>";
    if ($contato_employee['cellphone'])
        echo "<dt>Mobile number</dt><dd>{$contato_employee['cellphone']}</dd>";
    if ($contato_employee['email'])
        echo "<dt>Email</dt><dd>{$contato_employee['email']}</dd>";
    if ($employee['socialsecurity'])
        echo "<dt>Social security</dt><dd>{$employee['socialsecurity']}</dd>";
    if ($employee['driverlicense'])
    {
        echo "<dt>Driver license</dt><dd>{$employee['driverlicense']}</dd>";
        if ($employee['driverexp'])
            echo "<dt>Driver license expiration date</dt><dd>{$employee['driverexp']}</dd>";
    }
    if ($employee['obs'])
            echo "<dt>Observations</dt><dd>{$employee['obs']}</dd>";
    echo "</dl>";
}
echo "</div>";

if (!$admin_page)
{
    echo "<hr>";

    // Formulario para entrar com o periodo de tempo
    echo "<form id=periodo method=GET action=employee.php>";
    echo "<input type=HIDDEN value='{$employee['id']}' name='id'>";
    if (isset($_GET['period']))
            echo "<input type=HIDDEN value='{$_GET['period']}' name='period'>";
    echo "<label for=from>From:</label> <input id=from type=TEXT value='" . @$_GET['from'] . "' name='from' size=9>",
        "<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'from', 'chooserSpan1', 2000, 2020, Date.patterns.ShortDatePattern, false); \" alt='calendar'>",
        "<div id='chooserSpan1' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div>";
    echo "<label for=to>To:</label> <input id=to type=TEXT value='" . @$_GET['to'] . "' name='to' size=9>",
        "<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'to', 'chooserSpan2', 2000, 2020, Date.patterns.ShortDatePattern, false);\" alt='calendar'>",
        "<div id='chooserSpan2' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div><br>";
    echo "<label for=period>Period:</label> <select id=period name=period>";
    echo "<option value=0>Any</option>";
    echo "<option value=", LUNCH, (@$_GET['period'] == LUNCH? " selected=TRUE" : ""), ">{$PERIOD[LUNCH]}</option>";
    echo "<option value=", DINNER, (@$_GET['period'] == DINNER? " selected=TRUE" : ""), " >{$PERIOD[DINNER]}</option>";
    echo "<option value=", GRAVEYARD, (@$_GET['period'] == GRAVEYARD? " selected=TRUE" : ""), ">{$PERIOD[GRAVEYARD]}</option>";
    echo "</select><br>";

    echo "<label for=location>Subjects to location:</label> <select id=location name='location' >";
    echo "<option value=0 >----any----</option>";

    /* get name and id from all locations */
    $locations = get_all_locations();

    foreach ($locations as $loc)
    {
        echo	"<option value={$loc['id']} ";
        if (@$_GET['location']==$loc['id'])
        {
            echo "selected=SELECTED";
            $location_name = $loc['name'];
        }
        echo ">{$loc['name']}</option>";
    }
    unset($locations);
    echo "</select><br>";

    echo "<input type=SUBMIT value='submit' name='ok'>";
    echo "</form>";

    /* Includes employee table */
    flush();
    include('employee_table.php');

    if (!isset($_GET["print"]) && $employee['id'] == $_SESSION[site_id]['id'])
        echo "<div id=report_error><a href='report_error.php'><img src='img/exclamation.png' alt=''>Report an error</a></div>";

    unset($resultado, $employee);
}

// Finaliza pagina
pagina_fim();
?>
